<template>
  <!--  <div class="app-container">-->
  <div class="box-sty">
    <!-- <ShoppingList></ShoppingList> -->
    <div class="right-box">
      <div class="cancel-account-content">
        <div class="warning-message">
          <a-alert
            type="warning"
            show-icon
            :closable="false"
            message="Important Notice"
            description="Cancelling your account will permanently delete all your data, including order history and personal information."
          />
        </div>

        <a-form
          :model="form"
          :label-col="{ style: { width: '140px' } }"
          class="cancel-form"
        >
          <a-form-item label="Email">
            <a-input
              v-model:value="form.email"
              placeholder="Enter your email"
            />
          </a-form-item>
          <a-form-item label="Verification Code">
            <div style="display: flex;">
              <a-input
                v-model:value="form.verificationCode"
                placeholder="Enter the verification code"
                style="flex: 1; margin-right: 10px;"
              />
              <a-button
                :disabled="isCounting"
                @click="sendVerificationCode"
                style="width: 120px; background-color: #000; color: #fff; border: none;"
              >
                {{ isCounting ? `${countdown}s` : "Send Code" }}
              </a-button>
            </div>
            <div class="verification-tip" v-if="!isCounting && !form.verificationCode">
              Click "Send Code" to receive a verification code in your email
            </div>
          </a-form-item>
        </a-form>

        <div class="btn-box">
          <!-- <el-button @click="dialogVisible = false" style="border: 1px solid #000; color: #000; background: #fff;">
            Cancel
          </el-button> -->
          <a-button
            @click="handleCancelAccount"
            style="background-color: #000; color: #fff; border: none;"
          >
            Confirm Cancellation
          </a-button>
        </div>
      </div>

    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onUnmounted } from 'vue'
import { message } from 'ant-design-vue'
import { Local } from "@/utils/storage.ts";
import { signoutSendCode, cancelUserAccount } from "@/api/index.ts";
import { useUserStore } from '@/store/user'
import { useRouter } from 'vue-router'

const router = useRouter()
const userStore = useUserStore()
// 注销账号
// const dialogVisible = ref(false)
const form = ref({
  email: Local.get('userInfo')?.email || '',
  verificationCode: ''
})
// Countdown related
const countdown = ref(0);
const isCounting = ref(false);
let verificationTimer: ReturnType<typeof setInterval> | null = null;

// Send verification code
const sendVerificationCode = async () => {
  if (!form.value.email) {
    message.warning('Please enter your email');
    return;
  }

  try {
    // Start countdown
    isCounting.value = true;
    countdown.value = 60;

    // Clear previous timer
    if (verificationTimer) {
      clearInterval(verificationTimer);
    }

    // Set new timer
    verificationTimer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(verificationTimer!);
        isCounting.value = false;
      }
    }, 1000);

    const res = await signoutSendCode(form.value.email);
    if (res.code === 200) {
      message.success("Verification code sent successfully");
    } else {
      message.warning(res.msg || "Failed to send verification code");
      // Reset countdown if sending fails
      clearInterval(verificationTimer!);
      isCounting.value = false;
      countdown.value = 0;
    }
  } catch (error) {
    // Reset countdown on error
    if (verificationTimer) {
      clearInterval(verificationTimer);
    }
    isCounting.value = false;
    countdown.value = 0;
    message.error("Failed to send verification code");
  }
};

const handleCancelAccount = () => {
  if (!form.value.email || !form.value.verificationCode) {
    message.warning('Please fill in all fields');
    return;
  }

  cancelUserAccount({
    email: form.value.email,
    code: form.value.verificationCode
  }).then((res: any) => {
    if (res.code === 200) {
      message.success('Account cancelled successfully');
      // dialogVisible.value = false;
      setTimeout(() => {
        userStore.logout();
        router.push('/login');
      }, 1500);
    } else {
      message.error(res.msg || 'Failed to cancel account');
    }
  }).catch(() => {
    message.error('An error occurred');
  });
}

// Clean up timer when component unmounts
onUnmounted(() => {
  if (verificationTimer) {
    clearInterval(verificationTimer);
    isCounting.value = false;
    countdown.value = 0;
  }
});

// Reset form and timer when dialog closes
// watch(dialogVisible, (newVal) => {
//   if (!newVal) {
//     form.value.verificationCode = '';
//     if (verificationTimer) {
//       clearInterval(verificationTimer);
//       isCounting.value = false;
//       countdown.value = 0;
//     }
//   } else {
//     form.value.email = Local.get('userInfo')?.email || '';
//   }
// });
</script>


<style scoped lang="scss">
.box-sty {
  width: 100%;
  height: 64vh;
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
}

.right-box {
  padding: 56px 60px;
}

/* Cancel Account Dialog Styles */
:deep(.right-box) {
  .el-dialog__header {
    padding: 20px 25px;
    border-bottom: 1px solid #f0f0f0;
  }

  .el-dialog__title {
    font-size: 18px;
    font-weight: 600;
    color: #000;
  }

  .el-dialog__body {
    padding: 25px;
  }

  .cancel-account-content {
    .warning-message {
      margin-bottom: 25px;
    }

    .cancel-form {
      margin-top: 20px;
    }

    .verification-tip {
      margin-top: 8px;
      font-size: 12px;
      color: #909399;
      line-height: 1.4;
      margin-left: 20px;
    }
  }

  .btn-box {
    display: flex;
    justify-content: flex-end;
    gap: 15px;
    padding: 10px 0;
  }

  .el-button {
    padding: 10px 20px;
    font-weight: 500;
    transition: all 0.3s;

    &:hover {
      opacity: 0.85;
    }
  }
}
</style>
